package com.school;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.alibaba.fastjson.JSON;
import com.mhuang.school.starter.minio.EnableMinio;
import com.mhuang.school.starter.minio.core.MinioFrame;
import com.mhuang.school.starter.minio.util.ToolUtil;
import com.school.device.config.DahuaCofig;
import com.school.device.dynamic.DvIntellifHikvisonDevice;
import com.school.device.dynamic.MultiThreadSdk;
import com.school.device.util.DataConvertUtil;
import com.school.device.util.JsonUtil;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@EnableMinio
@EnableScheduling
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@ComponentScan(basePackages = { "com.school" })
public class SchoolSdkPushApplication {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(SchoolSdkPushApplication.class);
		app.setBannerMode(Banner.Mode.OFF);
		app.run(args);
	}
	
	@Autowired
	private DahuaCofig dahuaCofig;

	@Autowired
	private MinioFrame minioFrame;

	@Bean
	public CommandLineRunner commandLineRunner() throws Exception {
		return args -> {			
			Byte type = dahuaCofig.getType(); // 0:本地配置设备 1:拉取设备 37777端口
			if (type != 0) {//线上
				List<DvIntellifHikvisonDevice> devices = getDevices(dahuaCofig.getDeviceipUrl());				
				devices = devices.stream().filter(item->(item.getDeviceType()==1 || item.getDeviceType()==2)).collect(Collectors.toList());				
				if (devices != null)
					new MultiThreadSdk().start(devices, minioFrame, dahuaCofig.getPushUrl(),dahuaCofig.getDeviceipUrl());
			}
		};
	}

	private List<DvIntellifHikvisonDevice> getDevices(String deviceIpUrl) {
		if (ToolUtil.isEmpty(deviceIpUrl)) {
			System.err.println("拉取设备端口接口为空");
			log.error("拉取设备端口接口为空");
			return null;
		}
		HttpResponse response = HttpRequest.get(deviceIpUrl).execute();
		if (response.isOk()) {
			String body = response.body();
			if (ToolUtil.isNotEmpty(body)) {
				Map<String, Object> result = JsonUtil.toMap(body);
				if (DataConvertUtil.getObjectStr(result, "respCode").equalsIgnoreCase("10000000"))
					return JsonUtil.toBeans(JSON.toJSONString(result.get("data")), DvIntellifHikvisonDevice.class);
			}
		}
		System.err.println("请检查连接设备端口");
		log.error("请检查连接设备端口");
		return null;
	}

}
